package com.kalvan.web.feign;

import com.kalvan.client.system.SystemUtil;
import com.kalvan.web.feign.cache.FeignCacheService;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Target;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.annotation.Resource;

/**
 * Feign请求拦截器
 *
 * @author chenliang
 */
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
    public static final String PROD = "prod" ;
    @Resource
    private FeignCacheService feignCacheService;

    public FeignRequestInterceptor() {
        log.info("init FeignRequestInterceptor...");
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        Target<?> target = requestTemplate.feignTarget();
        String url = target.url();
        if (!PROD.equalsIgnoreCase(SystemUtil.constants.getProfile())) {
            String mockUrl = feignCacheService.getMockUrl(url);
            if (StringUtils.isNotBlank(mockUrl)) {
                log.info("mock请求:{} -> {}", url, mockUrl);
                //支持修改请求接口定义上的请求url
                requestTemplate.target(mockUrl);
                return;
            }
        }
        //支持修改请求接口定义上的请求url
        requestTemplate.target(url);
    }
}